<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>
</head>
<body>
<form onsubmit="return false;">

    <textarea id="req" style="width: 400px;height: 100px;"></textarea>
<input type="button" value="发送" onclick="send(document.getElementById('req').value)"/>

    <h3>服务端输出</h3>
    <textarea id="res" style="width: 400px;height: 100px;"></textarea>
    <input type="button" value="清空" onclick="document.getElementById('res').value=''" >
</form>



</body>

<script>
    var socket;
    var el = document.getElementById("res");

    if (window.WebSocket){
        socket = new WebSocket("ws://localhost:8899/ws");
        socket.onmessage = function (event){
            el.value = el.value + "\n" + event.data;
        }

        socket.onopen = function (event){
            el.value = "链接开启"
        }

        socket.onclose = function (event){
            el.value = "链接断开"
        }


    }else{
        alert("浏览器不支持")
    }

    function send(msg){
        if (!window.WebSocket){
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(msg);
        }else{
            alert("链接尚未开启");
        }
    }
</script>
</html>